from django.contrib.auth.hashers import make_password
from rest_framework.views import APIView
from rest_framework.response import Response

import re

from .models import User
from .serializer import UserModelSerializer


class RegisterView(APIView):
    """
    @ author: donghaiming
    @ date: 2020-10-26
    用户注册：需要提供以下数据
        用户名、密码、确认密码、邮箱
    """
    def post(self, request):
        """
        {'username': ['zhangsan'], 'password1': ['123'], 'password2': ['123'], 'email': ['zhangsan123@qq.com']}
        """
        username = request.data.get('username')
        password1 = request.data.get('password1')
        password2 = request.data.get('password2')
        email = request.data.get('email')

        # 判断数据完整
        if not all([username, password1, password2, email]):
            return Response({'msg': '数据不完整', 'code': 400})

        # 正则验证邮箱
        ex_email = re.compile(r'^[\w][a-zA-Z1-9.]{4,19}@[a-zA-Z0-9]{2,3}.com')
        if not re.match(ex_email, email):
            return Response({'msg': '邮箱格式不正确', 'code': 400})

        # 判断用户是否存在
        user_obj = User.objects.filter(username=username).first()
        if user_obj:
            return Response({'msg': '用户已注册', 'code': 400})

        # 两次密码验证
        if password1 == password2:
            # 构造数据
            user_data = {'username': username, 'password': make_password(password1), 'email': email}
            user_serializer = UserModelSerializer(data=user_data)
            # 校验数据
            if user_serializer.is_valid():
                user_serializer.save()
                return Response({'msg': '注册成功', 'code': 200})
            else:
                return Response({'error': user_serializer.errors, 'code': 400})
        else:
            return Response({'msg': '两次密码不一致', 'code': 400})
